package com.hui.account.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.hui.account.R;
import com.hui.account.activity.UserAddActivity;
import com.hui.account.adapter.UserAdapter;
import com.hui.account.database.SQLManage;
import com.hui.account.entity.UserEntity;
import com.hui.account.utils.ButtonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 客户选择：记一笔欠款单选择客户专用
 */
public class UserCopyActivity extends AppCompatActivity implements View.OnClickListener {

    Context context;

    TextView searchEmpty;

    ListView userList; // 用户列表

    EditText searchUserEdit; // 搜索

    Button addUserBtn, backBtn;

    List<UserEntity> data; // 客户数据

    UserAdapter adapter;

    SharedPreferences preferences; // preferences：共享参数，存储选中的用户信息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        setContentView(R.layout.activity_user);

        // 1、设置屏幕顶部字体颜色
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);

        // 2、初始化页面
        initView();

        // 3、preferences：共享参数初始化
        preferences = getSharedPreferences("shareParam", Context.MODE_PRIVATE);

        // 4、设置 ListView点击事件
        onClickUserList();

        // 5、引入用户适配器
        data = new ArrayList<>();
        adapter = new UserAdapter(this, data);
        userList.setAdapter(adapter);

        userList.setEmptyView(searchEmpty);
    }

    /**
     * Activity加载时执行
     */
    @Override
    protected void onResume() {
        super.onResume();

        // 加载客户数据
        loadUserData();
    }

    /**
     * 初始化页面
     */
    private void initView() {
        userList = findViewById(R.id.user_list);
        backBtn = findViewById(R.id.user_back);
        addUserBtn = findViewById(R.id.user_add);
        searchUserEdit = findViewById(R.id.user_search);
        searchEmpty = findViewById(R.id.user_search_empty);

        backBtn.setOnClickListener(this);
        addUserBtn.setOnClickListener(this);
        searchUserEdit.setOnClickListener(this);
    }

    /**
     * 加载客户数据
     */
    private void loadUserData() {
        List<UserEntity> list = getUsers();
        if (list.size() > 0) {
            data.clear();
            data.addAll(list);
            adapter.notifyDataSetChanged();
        } else {
            data.clear();
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 用户适配器点击事件
     */
    private void onClickUserList() {
        userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // 1、获取到当前记录
                UserEntity user = data.get(i);

                // 2、将数据存入共享参数
                SharedPreferences.Editor edit = preferences.edit();
                edit.putString("selectUser", new Gson().toJson(user));
                edit.commit();

                finish();
            }
        });
    }

    /**
     * 分页查询数据
     */
    public List<UserEntity> getUsers() {
        int curPage = 0; // 起始页码
        int pageSize = 500; // 每页查询最大数
        List<UserEntity> list = new ArrayList<>();
        boolean flag = true;
        while (flag) {
            List<UserEntity> records = SQLManage.getUsers(0, curPage, pageSize);
            if (records.size() > 0) {
                list.addAll(records);
                if (records.size() == pageSize) {
                    curPage += pageSize;
                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
        return list;
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_back:
                finish();
                break;
            case R.id.user_add:
                if (!ButtonUtils.isFastDoubleClick())
                    startActivity(new Intent(this, UserAddActivity.class));

                break;
            case R.id.user_search:
                if (!ButtonUtils.isFastDoubleClick()) {
                    searchUserEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                        @Override
                        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                            if ((actionId == EditorInfo.IME_ACTION_UNSPECIFIED || actionId == EditorInfo.IME_ACTION_SEARCH) && keyEvent != null) {
                                // 搜索客户
                                String value = searchUserEdit.getText().toString().trim();
                                if (!TextUtils.isEmpty(value)) {
                                    List<UserEntity> users = SQLManage.getUserByNameVague(value);
                                    if (users.size() > 0) {
                                        data.clear();
                                        data.addAll(users);
                                        adapter.notifyDataSetChanged();
                                    } else {
                                        data.clear();
                                        adapter.notifyDataSetChanged();
                                    }
                                } else {
                                    List<UserEntity> list = getUsers();
                                    if (list.size() > 0) {
                                        data.clear();
                                        data.addAll(list);
                                        adapter.notifyDataSetChanged();
                                    } else {
                                        data.clear();
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                                return true;
                            }
                            return false;
                        }
                    });
                }
                break;
        }
    }
}